<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import {
  ArrowLeftOutlined,
  DollarOutlined,
  GlobalOutlined,
  LineChartOutlined,
  PercentageOutlined,
  ReloadOutlined
} from '@ant-design/icons-vue';
import { Button, Card, Descriptions, Empty, Space, Spin, Table, Tabs, Tag, message } from 'ant-design-vue';
import { fetchMarketDataById } from '@/service/api/market-data';
import { useRouterPush } from '@/hooks/common/router';
import RateCurveDisplay from './modules/RateCurveDisplay.vue';
import VolatilitySurfaceDisplay from './modules/VolatilitySurfaceDisplay.vue';
const { routerPushByKey } = useRouterPush();
const route = useRoute();

// 监听路由参数变化
const id = ref(route.query.id as string);
watch(
  () => route.query.id,
  newId => {
    if (newId && newId !== id.value) {
      id.value = newId as string;
      fetchData();
    }
  },
  { immediate: true }
);

// 响应式数据
const loading = ref(false);
const marketData = ref<any>(null);
const activeTab = ref('basic');

// 表格列定义

const spotPriceColumns = [
  { title: '货币对', dataIndex: 'name', key: 'name', width: 120 },
  { title: '日期', dataIndex: 'spotDate', key: 'spotDate' },
  { title: '买入价', dataIndex: 'quote.bid', key: 'bid' },
  { title: '卖出价', dataIndex: 'quote.ask', key: 'ask' },
  { title: '中间价', dataIndex: 'quote.mid', key: 'mid' }
];

const currencyPairColumns = [
  { title: '货币对', dataIndex: 'name', key: 'name', width: 120 },
  { title: '基础货币', dataIndex: 'baseCurrency', key: 'baseCurrency' },
  { title: '报价货币', dataIndex: 'quoteCurrency', key: 'quoteCurrency' },
  { title: '标的货币', dataIndex: 'underlyingCurrency', key: 'underlyingCurrency' },
  { title: '收益率曲线1', dataIndex: 'rateCurve1', key: 'rateCurve1' },
  { title: '收益率曲线2', dataIndex: 'rateCurve2', key: 'rateCurve2' }
];

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch {
    return dateStr;
  }
};

// 计算属性：即期汇率数据
const spotPriceData = computed(() => {
  if (!marketData.value?.spotPriceMap) return [];

  return Object.entries(marketData.value.spotPriceMap).map(([name, data]: [string, any]) => ({
    ...data,
    name,
    spotDate: formatDate(data.spotDate),
    key: name
  }));
});

// 计算属性：货币对配置数据
const currencyPairData = computed(() => {
  if (!marketData.value?.currencyPairConfig?.currencyPairParameterMap) return [];

  return Object.entries(marketData.value.currencyPairConfig.currencyPairParameterMap).map(
    ([name, data]: [string, any]) => ({
      ...data,
      key: name,
      calendarList: data.calendarList ? data.calendarList.join(', ') : ''
    })
  );
});

// 获取市场数据详情
async function fetchData() {
  if (!id.value) {
    message.error('缺少市场数据ID参数');
    return;
  }

  try {
    loading.value = true;
    const response = await fetchMarketDataById(id.value);
    console.info(response);
    if (response) {
      marketData.value = response.data;
    } else {
      marketData.value = null;
      message.warning('未找到对应的市场数据');
    }
  } catch (error) {
    console.log('获取市场数据详情失败:', error);
    message.error('获取市场数据详情失败，请稍后重试');
    marketData.value = null;
  } finally {
    loading.value = false;
  }
}

// 返回列表
const goBack = () => {
  routerPushByKey('valuation_market-data');
};

// 获取类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    INTEREST_RATE: 'blue',
    EXCHANGE_RATE: 'green',
    STOCK_PRICE: 'orange',
    COMMODITY_PRICE: 'purple',
    VOLATILITY: 'red',
    CREDIT_SPREAD: 'cyan'
  };
  return colorMap[type] || 'default';
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="market-data-detail-container">
    <Card title="市场数据详情" :bordered="false">
      <template #extra>
        <Space>
          <Button @click="goBack">
            <template #icon>
              <ArrowLeftOutlined />
            </template>
            返回列表
          </Button>
          <Button type="primary" :loading="loading" @click="fetchData">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新数据
          </Button>
        </Space>
      </template>

      <div v-if="loading" class="loading-container">
        <Spin size="large" tip="加载中..." />
      </div>

      <div v-else-if="marketData" class="detail-content">
        <Tabs v-model:active-key="activeTab">
          <Tabs.TabPane key="basic" tab="基本信息">
            <!-- 基本信息 -->
            <Card class="info-card" :bordered="false">
              <Descriptions :column="2" bordered>
                <Descriptions.Item label="ID">
                  <Tag color="blue">{{ marketData.id || marketData.marketId }}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="市场数据类型">
                  <Tag :color="getTypeColor(marketData.marketDataType)">
                    {{ marketData.marketDataType || '综合市场数据' }}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="货币">
                  <Tag v-if="marketData.currency" color="green">
                    {{ marketData.currency }}
                  </Tag>
                  <span v-else>-</span>
                </Descriptions.Item>
                <Descriptions.Item label="基准日期">
                  <span v-if="marketData.horizonDate">
                    {{ formatDate(marketData.horizonDate) }}
                  </span>
                  <span v-else>-</span>
                </Descriptions.Item>
                <Descriptions.Item label="最后更新时间">
                  <span v-if="marketData.lastUpdated || marketData.updateTime">
                    {{ formatDate(marketData.lastUpdated || marketData.updateTime) }}
                  </span>
                  <span v-else>-</span>
                </Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag :color="marketData.status === 1 ? 'green' : 'red'">
                    {{ marketData.status === 1 ? '有效' : '无效' }}
                  </Tag>
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <!-- JSON 原始数据 -->
            <Card class="info-card" :bordered="false">
              <div class="json-viewer">
                <pre class="json-content">{{ JSON.stringify(marketData, null, 2) }}</pre>
              </div>
            </Card>
          </Tabs.TabPane>

          <!-- 收益率曲线 -->
          <Tabs.TabPane key="rateCurve" tab="收益率曲线" :disabled="!marketData.quoteRateCurveMap">
            <template #tab>
              <span>
                <LineChartOutlined />
                收益率曲线
              </span>
            </template>
            <RateCurveDisplay :rate-curve-map="marketData.quoteRateCurveMap || {}" />
          </Tabs.TabPane>

          <!-- 波动率曲面 -->
          <Tabs.TabPane key="volatility" tab="波动率曲面" :disabled="!marketData.quoteVolatilitySurfaceMap">
            <template #tab>
              <span>
                <PercentageOutlined />
                波动率曲面
              </span>
            </template>
            <VolatilitySurfaceDisplay :volatility-surface-map="marketData.quoteVolatilitySurfaceMap || {}" />
          </Tabs.TabPane>

          <!-- 即期汇率 -->
          <Tabs.TabPane key="spotPrice" tab="即期汇率" :disabled="!marketData.spotPriceMap">
            <template #tab>
              <span>
                <DollarOutlined />
                即期汇率
              </span>
            </template>
            <Card class="info-card" :bordered="false">
              <div v-if="Object.keys(marketData.spotPriceMap || {}).length === 0" class="empty-data">
                <Empty description="暂无即期汇率数据" />
              </div>
              <div v-else>
                <Table :columns="spotPriceColumns" :data-source="spotPriceData" :pagination="false" size="small">
                  <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'spotDate'">
                      <span>{{ formatDate(text) }}</span>
                    </template>
                    <template v-else-if="column.key === 'bid'">
                      <span>{{ record.quote?.bid ? record.quote.bid.toFixed(6) : '-' }}</span>
                    </template>
                    <template v-else-if="column.key === 'ask'">
                      <span>{{ record.quote?.ask ? record.quote.ask.toFixed(6) : '-' }}</span>
                    </template>
                    <template v-else-if="column.key === 'mid'">
                      <span>{{ record.quote?.mid ? record.quote.mid.toFixed(6) : '-' }}</span>
                    </template>
                  </template>
                </Table>
              </div>
            </Card>
          </Tabs.TabPane>

          <!-- 货币对配置 -->
          <Tabs.TabPane key="currencyPair" tab="货币对配置" :disabled="!marketData.currencyPairConfig">
            <template #tab>
              <span>
                <GlobalOutlined />
                货币对配置
              </span>
            </template>
            <Card class="info-card" :bordered="false">
              <div v-if="!marketData.currencyPairConfig?.currencyPairParameterMap" class="empty-data">
                <Empty description="暂无货币对配置数据" />
              </div>
              <div v-else>
                <Table
                  :columns="currencyPairColumns"
                  :data-source="currencyPairData"
                  :pagination="false"
                  size="small"
                  :scroll="{ x: 1000 }"
                ></Table>

                <div
                  v-for="(data, name) in marketData.currencyPairConfig.currencyPairParameterMap"
                  :key="name"
                  class="currency-pair-detail"
                >
                  <h3 class="curve-title">{{ name }} 详细配置</h3>
                  <Descriptions bordered :column="2" size="small">
                    <Descriptions.Item label="基础货币">{{ data.baseCurrency }}</Descriptions.Item>
                    <Descriptions.Item label="报价货币">{{ data.quoteCurrency }}</Descriptions.Item>
                    <Descriptions.Item label="标的货币">{{ data.underlyingCurrency }}</Descriptions.Item>
                    <Descriptions.Item label="收益率曲线1">{{ data.rateCurve1 }}</Descriptions.Item>
                    <Descriptions.Item label="收益率曲线2">{{ data.rateCurve2 }}</Descriptions.Item>
                    <Descriptions.Item label="Delta中的溢价">
                      <Tag :color="data.premiumInDelta ? 'green' : 'red'">
                        {{ data.premiumInDelta ? '是' : '否' }}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="使用营业日">
                      <Tag :color="data.useBusinessDate ? 'green' : 'red'">
                        {{ data.useBusinessDate ? '是' : '否' }}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="波动率约定">{{ data.volatilityConvention }}</Descriptions.Item>
                    <Descriptions.Item label="ATM使用远期">
                      <Tag :color="data.atmUseForward ? 'green' : 'red'">
                        {{ data.atmUseForward ? '是' : '否' }}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item label="即期因子">{{ data.spotFactor }}</Descriptions.Item>
                    <Descriptions.Item label="掉期单位">{{ data.swapUnit }}</Descriptions.Item>
                    <Descriptions.Item label="日历列表">
                      {{ data.calendarList ? data.calendarList.join(', ') : '-' }}
                    </Descriptions.Item>
                  </Descriptions>
                </div>
              </div>
            </Card>
          </Tabs.TabPane>
        </Tabs>
      </div>

      <div v-else class="empty-container">
        <Empty description="未找到市场数据" />
      </div>
    </Card>
  </div>
</template>

<style scoped>
.market-data-detail-container {
  padding: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  margin-bottom: 16px;
}

.info-card:last-child {
  margin-bottom: 0;
}

.identifier {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.value {
  font-weight: 600;
  color: #1890ff;
}

.properties-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.property-item {
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  padding: 12px;
  background-color: #fafafa;
}

.property-label {
  font-weight: 600;
  color: #666;
  margin-bottom: 8px;
  font-size: 13px;
}

.property-value {
  color: #333;
}

.number-value {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  color: #1890ff;
  font-weight: 600;
}

.json-viewer {
  background-color: #f8f8f8;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 16px;
  overflow-x: auto;
}

.json-content {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  margin: 0;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

.curve-section {
  margin-bottom: 24px;
}

.curve-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #1890ff;
  border-left: 4px solid #1890ff;
  padding-left: 10px;
}

.smile-curve {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.smile-curve h4 {
  margin-bottom: 12px;
  font-size: 14px;
  color: #333;
}

.empty-data {
  padding: 24px;
  text-align: center;
}

.currency-pair-detail {
  margin-top: 24px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
}

:deep(.ant-tabs-tab) {
  padding: 8px 16px;
}

:deep(.ant-tabs-tab-btn) {
  font-size: 14px;
}

:deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  color: #1890ff;
  font-weight: 600;
}

:deep(.ant-table-small) {
  font-size: 12px;
}

:deep(.ant-table-small .ant-table-thead > tr > th) {
  background-color: #f5f5f5;
  font-weight: 600;
}
</style>
